<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="简讯" prop="content">
      <el-input v-model="ruleForm.content" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >Submit</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent, reactive, Ref, ref, inject } from "vue";
import type { FormInstance } from "element-plus";
export default defineComponent({
  setup() {
    interface RuleForm {
      content: string;
    }
    const list: any[] = inject("list", []);
    const ruleForm: RuleForm = inject("ruleForm", { content: "" });
    const state: any = inject("state");
    const ruleFormRef = ref<FormInstance>();

    const rules = reactive({
      content: [{ required: true, trigger: "blur" }],
    });
    const submitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          if (state.type == "add") {
            list.push({
              content: ruleForm.content,
            });
          } else {
            list[state.index].content = ruleForm.content;
            state.type = "add";
          }

          resetForm(formEl);
          console.log("submit!");
        } else {
          console.log("error submit!");
          return false;
        }
      });
    };

    const resetForm = (formEl: FormInstance | undefined) => {
      console.log(formEl);

      if (!formEl) return;
      formEl.resetFields();
    };
    return {
      ruleFormRef,
      ruleForm,
      rules,
      submitForm,
      resetForm,
    };
  },
});
</script>

<style></style>
